package com.hwpt.chesedemo.presentation.component

import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.graphics.drawscope.DrawScope
import com.hwpt.chesedemo.presentation.theme.BoardBorder
import com.hwpt.chesedemo.presentation.theme.DarkSquare
import com.hwpt.chesedemo.presentation.theme.LightSquare
import kotlin.math.PI
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sin

@Composable
fun ChessBoard(
    boardState: List<List<ChessPiece?>>,
    selectedPiece: Position?,
    validMoves: List<Position>,
    highlightedMove: Pair<Position, Position>?, // 高亮移动轨迹
    onPieceSelected: (row: Int, col: Int) -> Unit,
    modifier: Modifier = Modifier,
    boardSize: Dp? = null,
) {
    val configuration = LocalConfiguration.current
    val calculatedBoardSize = boardSize ?: run {
        val screenWidth = configuration.screenWidthDp.dp
        val screenHeight = configuration.screenHeightDp.dp
        minOf(screenWidth, screenHeight) * 0.85f
    }

    val squareSize = calculatedBoardSize / 8
    val pieceFontSize = squareSize.value * 0.6f

    // 动画效果
    val infiniteTransition = rememberInfiniteTransition()
    val animatedAlpha by infiniteTransition.animateFloat(
        initialValue = 0.3f,
        targetValue = 0.8f,
        animationSpec = infiniteRepeatable(
            animation = tween(1000, easing = LinearEasing),
            repeatMode = RepeatMode.Reverse
        )
    )

    val animatedPulse by infiniteTransition.animateFloat(
        initialValue = 0.8f,
        targetValue = 1.2f,
        animationSpec = infiniteRepeatable(
            animation = tween(800, easing = LinearEasing),
            repeatMode = RepeatMode.Reverse
        )
    )

    Box(
        modifier = modifier
            .size(calculatedBoardSize)
            .background(BoardBorder)
            .padding(2.dp)
    ) {
        LazyVerticalGrid(
            columns = GridCells.Fixed(8),
            modifier = Modifier.fillMaxSize()
        ) {
            itemsIndexed(boardState.flatten()) { index, piece ->
                val row = index / 8
                val col = index % 8
                val isLightSquare = (row + col) % 2 == 0
                val isSelected = selectedPiece?.row == row && selectedPiece.col == col
                val isValidMove = validMoves.any { it.row == row && it.col == col }

                // 高亮移动轨迹逻辑
                val isHighlightedFrom = highlightedMove?.first?.row == row &&
                        highlightedMove.first?.col == col
                val isHighlightedTo = highlightedMove?.second?.row == row &&
                        highlightedMove.second?.col == col
                val isHighlightedMove = isHighlightedFrom || isHighlightedTo

                Box(
                    modifier = Modifier
                        .aspectRatio(1f)
                        .background(
                            when {
                                isHighlightedFrom -> Color.Yellow.copy(alpha = 0.6f) // 起始位置用黄色
                                isHighlightedTo -> Color.Green.copy(alpha = 0.6f)    // 目标位置用绿色
                                isSelected -> Color.Green.copy(alpha = 0.5f)
                                isValidMove -> Color.Blue.copy(alpha = 0.3f)
                                else -> if (isLightSquare) LightSquare else DarkSquare
                            }
                        )
                        .clickable { onPieceSelected(row, col) },
                    contentAlignment = Alignment.Center
                ) {
                    piece?.let { chessPiece ->
                        Text(
                            text = getPieceSymbol(chessPiece),
                            fontSize = pieceFontSize.sp,
                            color = if (chessPiece.player == Player.WHITE) Color.White else Color.Black,
                            fontWeight = FontWeight.Medium
                        )
                    }
                    if (isValidMove && piece == null) {
                        Box(
                            modifier = Modifier
                                .size(squareSize * 0.2f)
                                .background(
                                    Color.Blue.copy(alpha = 0.5f),
                                    shape = androidx.compose.foundation.shape.CircleShape
                                )
                        )
                    }

                    // 在高亮格子上添加特殊标记
                    if (isHighlightedMove) {
                        Box(
                            modifier = Modifier
                                .size(squareSize * 0.3f * animatedPulse)
                                .background(
                                    if (isHighlightedFrom) Color.Red.copy(alpha = animatedAlpha)
                                    else Color.Green.copy(alpha = animatedAlpha),
                                    shape = androidx.compose.foundation.shape.CircleShape
                                )
                        )
                    }
                }
            }
        }

        // 绘制动画移动轨迹连线
        highlightedMove?.let { (from, to) ->
            androidx.compose.foundation.Canvas(
                modifier = Modifier.fillMaxSize()
            ) {
                val squareWidth = size.width / 8
                val squareHeight = size.height / 8

                // 计算起点和终点的中心坐标
                val startX = from.col * squareWidth + squareWidth / 2
                val startY = from.row * squareHeight + squareHeight / 2
                val endX = to.col * squareWidth + squareWidth / 2
                val endY = to.row * squareHeight + squareHeight / 2

                // 使用动画alpha值
                val animatedLineColor = Color(0xFFFF6B35).copy(alpha = animatedAlpha)
                val animatedStartColor = Color.Red.copy(alpha = animatedAlpha)
                val animatedEndColor = Color.Green.copy(alpha = animatedAlpha)

                // 绘制连线
                drawLine(
                    color = animatedLineColor,
                    start = androidx.compose.ui.geometry.Offset(startX, startY),
                    end = androidx.compose.ui.geometry.Offset(endX, endY),
                    strokeWidth = 6f * animatedPulse,
                    cap = androidx.compose.ui.graphics.StrokeCap.Round
                )

                // 绘制箭头头部
                drawArrowHead(
                    start = androidx.compose.ui.geometry.Offset(startX, startY),
                    end = androidx.compose.ui.geometry.Offset(endX, endY),
                    color = animatedLineColor,
                    headSize = 16f * animatedPulse
                )

                // 绘制动画的起点和终点标记
                drawCircle(
                    color = animatedStartColor,
                    center = androidx.compose.ui.geometry.Offset(startX, startY),
                    radius = 10f * animatedPulse
                )

                drawCircle(
                    color = animatedEndColor,
                    center = androidx.compose.ui.geometry.Offset(endX, endY),
                    radius = 10f * animatedPulse
                )

                // 添加移动轨迹的光晕效果
                drawCircle(
                    color = animatedLineColor.copy(alpha = animatedAlpha * 0.3f),
                    center = androidx.compose.ui.geometry.Offset(startX, startY),
                    radius = 15f * animatedPulse
                )

                drawCircle(
                    color = animatedLineColor.copy(alpha = animatedAlpha * 0.3f),
                    center = androidx.compose.ui.geometry.Offset(endX, endY),
                    radius = 15f * animatedPulse
                )
            }
        }
    }
}

// 绘制箭头头部的扩展函数
private fun DrawScope.drawArrowHead(
    start: androidx.compose.ui.geometry.Offset,
    end: androidx.compose.ui.geometry.Offset,
    color: Color,
    headSize: Float
) {
    val angle = atan2(end.y - start.y, end.x - start.x)

    // 箭头头部的两个点
    val arrowPoint1 = androidx.compose.ui.geometry.Offset(
        end.x - headSize * cos(angle - PI / 6).toFloat(),
        end.y - headSize * sin(angle - PI / 6).toFloat()
    )

    val arrowPoint2 = androidx.compose.ui.geometry.Offset(
        end.x - headSize * cos(angle + PI / 6).toFloat(),
        end.y - headSize * sin(angle + PI / 6).toFloat()
    )

    // 绘制箭头头部
    drawLine(
        color = color,
        start = end,
        end = arrowPoint1,
        strokeWidth = 6f,
        cap = androidx.compose.ui.graphics.StrokeCap.Round
    )

    drawLine(
        color = color,
        start = end,
        end = arrowPoint2,
        strokeWidth = 6f,
        cap = androidx.compose.ui.graphics.StrokeCap.Round
    )
}

private fun getPieceSymbol(piece: ChessPiece): String {
    return when (piece.type) {
        PieceType.PAWN -> if (piece.player == Player.WHITE) "♙" else "♟"
        PieceType.ROOK -> if (piece.player == Player.WHITE) "♖" else "♜"
        PieceType.KNIGHT -> if (piece.player == Player.WHITE) "♘" else "♞"
        PieceType.BISHOP -> if (piece.player == Player.WHITE) "♗" else "♝"
        PieceType.QUEEN -> if (piece.player == Player.WHITE) "♕" else "♛"
        PieceType.KING -> if (piece.player == Player.WHITE) "♔" else "♚"
    }
}